﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Bamboo.Utils
{
    /// <summary>
    /// 环境变量公共函数
    /// </summary>
    public static class EnvUtils
    {
        /// <summary>
        /// 获取环境变量的值，如不存在则报错
        /// </summary>
        /// <param name="name">环境变量名</param>
        /// <returns></returns>
        /// <exception cref="Exception">指定的环境变量不存在</exception>
        public static string GetEnv(string name)
        {
            string v = Environment.GetEnvironmentVariable(name);
            if (v == null)
                throw new Exception("指定的环境变量不存在：" + name);
            v = Bamboo.Utils.Encrypt.DES3Decrypt(v);
            return v;
        }
        /// <summary>
        /// 获取环境变量的值，如不存在则返回默认值
        /// </summary>
        /// <param name="name">环境变量名</param>
        /// <param name="defaultValue">默认值</param>
        /// <returns></returns>
        public static string GetEnv(string name, string defaultValue)
        {
            string v = Environment.GetEnvironmentVariable(name);
            if (v == null)
                return defaultValue;
            v = Bamboo.Utils.Encrypt.DES3Decrypt(v);
            return v;
        }


        public static int GetEnvInt(string name, int defaultValue)
        {
            string v = Environment.GetEnvironmentVariable(name);
            if (v == null) return defaultValue;
            int v2;
            if (int.TryParse(v, out v2))
            {
                return v2;
            }
            else
            {
                return defaultValue;
            }
        }

        public static bool GetEnvBool(string name, bool defaultValue)
        {
            string v = Environment.GetEnvironmentVariable(name);
            if (string.IsNullOrWhiteSpace(v)) return defaultValue;
            v = v.ToLower();
            if (v == "true" || v == "1") return true;
            if (v == "false" || v == "0") return false;
            return defaultValue;
        }


        public static void SetEnv(string name, string value)
        {
            Environment.SetEnvironmentVariable(name, value);
        }
    }
}
